// 载入外挂
var gulp = require('gulp'),
    plumber = require('gulp-plumber'),
    imagemin = require('gulp-imagemin'),
    clean = require('gulp-clean'),
    cleanCss = require('gulp-clean-css'),
    uglify = require('gulp-uglify'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    // babel = require('gulp-babel'),
    fileinclude = require('gulp-file-include'),
    browserSync = require('browser-sync').create(),
    loadPlugins = require('gulp-load-plugins')(),  //快速引用插件 插件模块化
    spriter = require('gulp-css-spriter'),
    webpack = require('webpack-stream');

// 不处理第三方框架 原样输出
gulp.task('lib', function() {
  return gulp.src('src/lib/**/*')
  .pipe(gulp.dest('./dist/lib'))
})
// css
gulp.task('css', function() {
  return gulp.src('src/css/**/*.css')
  // .pipe(cleanCss()) // 压缩css
  .pipe(gulp.dest('./dist/css'))
});
// 脚本
// gulp.task('scripts', function() {
//   return gulp.src('src/js/**/*.js')
//   .pipe(babel()) // es6 转 es5
//   // .pipe(uglify()) // 压缩js
//   .pipe(gulp.dest('./dist/js'))
// });
gulp.task('scripts', function() {
  return gulp.src('src/js/**/*.js')
  .pipe(webpack(require(__dirname + '/webpack.config.js')))
  .pipe(gulp.dest('dist/js'));
});
// 图片
gulp.task('images', function() {
  return gulp.src('src/images/**/*.{png,jpg,gif,ico}')
  .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
  .pipe(imagemin())
  .pipe(gulp.dest('dist/images/'))
  .pipe(notify({ message: 'Images task complete' }));
});

//html
gulp.task('html', function() {
  return gulp.src('src/**/*.html')
  .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
  }))
  .pipe(gulp.dest('dist/'))
  .pipe(notify({ message: 'html task complete' }));
});
// 清理
gulp.task('clean', function() {
  return gulp.src(['dist/css', 'dist/js', 'dist/images'], { read: false })
  .pipe(clean());
});

// 重新编译打包
gulp.task('init', ['clean'], function() {
  gulp.start('lib');
  gulp.start('css');
  gulp.start('scripts');
  gulp.start('images');
  gulp.start('html');
});
// 静态服务器
gulp.task('browser-sync', function() {
    browserSync.init({
        // proxy: "127.0.0.2",
        files: "**", //监听整个项目
        server: {
          baseDir: "./dist/"
        }
    });
});

//设置看守
gulp.task('watch', function() {

    // 看守所有.css
    gulp.watch('src/css/**/*.css', ['css']);

    // 看守所有.js档
    gulp.watch('src/js/**/*.js', ['scripts']);

    // 看守所有图片档
    gulp.watch('src/images/**/*', ['images']);

    //看守html
    gulp.watch('src/**/*.html', ['html']);

});

//执行运行
gulp.task('default', ["watch", "browser-sync"]);